package com.exercise.AndroidCamera;
/*
기능 : 로그인 액티비티에서의 화면과 기능들이 담겨있음
작성 : 하드캔
완료일 : 2014.09.26 
	*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import android.R.string;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.PatternMatcher;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends BaseActivity {
	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	private static final String[] DUMMY_CREDENTIALS = new String[] {
			"foo@example.com:hello", "bar@example.com:world" };

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_TEXT = "com.example.android.authenticatordemo.extra.TEXT";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mID;
	private String mPassword;

	// UI references.
	private EditText mIDView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// Start splash activity.
		startActivity(new Intent(this, SplashActivity.class));
				
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		// Set up the login form.
		mID = getIntent().getStringExtra(EXTRA_TEXT);
		mIDView = (EditText) findViewById(R.id.ID);
		mIDView.setText(mID);

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		findViewById(R.id.login_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});
		
		findViewById(R.id.register_button).setOnClickListener(
				new View.OnClickListener() {
					
					@Override
					public void onClick(View view) {
						// TODO Auto-generated method stub
				    	Intent mIntent = new Intent(LoginActivity.this, RegisterActivity.class);
				        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			    		startActivity(mIntent);

					//	startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
					}
				});
		getActionBar().hide();
	}


	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mIDView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mID = mIDView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mID)) {
			mIDView.setError(getString(R.string.error_field_required));
			focusView = mIDView;
			cancel = true;
		} 

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_logging_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute();
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.

			try {
				// Simulate network access.
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				return false;
			}

			for (String credential : DUMMY_CREDENTIALS) {
				String[] pieces = credential.split(":");
				if (pieces[0].equals(mID)) {
					// Account exists, return true if the password matches.
					return pieces[1].equals(mPassword);
				}
			}

			// TODO: register the new account here.
			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			showProgress(false);

			if (success) {
				LoginAsyncTask login_asyn = new LoginAsyncTask();
				login_asyn.execute();
				
			} else {
				mPasswordView
						.setError(getString(R.string.error_incorrect_password));
				mPasswordView.requestFocus();
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}
	}
	
	public class LoginAsyncTask extends AsyncTask<String, String, String>{
	
		public LoginAsyncTask() {
			// TODO Auto-generated constructor stub
		}
		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String loginId = mIDView.getText().toString();
        	String loginPasswd = mPasswordView.getText().toString();
            
        	String[] result = this.login(LoginActivity.this, loginId, loginPasswd);

        	if(result[0].equals("error")){
        		Log.e("result", result[1]);
        		return result[1];
			}
			

			
			
			return null;
		}
		@Override
    	protected void onPostExecute(String result) {
    		// TODO Auto-generated method stub
    		super.onPostExecute(result);
    		
    		if(result != null){
    			Toast.makeText(LoginActivity.this, "로그인에 실패하였습니다.", Toast.LENGTH_SHORT).show();
    		}
    		mIDView.setText("");
            mPasswordView.setText("");
    		onCancelled();
    	}
		
		protected String[] login(Context context, String login_id, String login_passwd){
			String pString = null;
			HttpURLConnection conn = null;
			BufferedReader br = null;
			
			String[] result = new String[2];
			result[0] = "error"; //JSON flag
			result[1] = null; //message
			
			try{
	        	StringBuilder builder = new StringBuilder();
	        	
	        	URL url = new URL("http://54.199.194.197/login.php");
	        	conn = (HttpURLConnection)url.openConnection();
	        	
	        	if(conn != null){
	        		conn.setConnectTimeout(15000);	
	        		conn.setReadTimeout(15000);
	        		conn.setDefaultUseCaches(false); 
	            	conn.setDoInput(true); 
	            	conn.setDoOutput(true);  
	            	conn.setRequestMethod("POST");
	            	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
	            	
	            	StringBuffer buffer = new StringBuffer();
	                buffer.append("user_id").append("=").append(login_id).append("&");                 
	                buffer.append("password").append("=").append(login_passwd);
	                
	                OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	                PrintWriter writer = new PrintWriter(outStream);
	                writer.write(buffer.toString());
	                writer.flush();
	                
	                InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
	                br = new BufferedReader(inputStream);
	               
	            	String line;
	            	while((line = br.readLine()) != null){
	            	   builder.append(line);
	            	}
	               
	            	br.close();
	            	
	            	
	            	pString =  builder.toString();
	            	
	            	if(pString.equals("success")){
	            		Log.d("success", pString);
	            		result[0] = "success";
	            		result[1] = pString.replace("success:", "");
				    	Intent mIntent = new Intent(LoginActivity.this, MainActivity.class);
				        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				        mIntent.putExtra("userID", login_id);
			    		startActivity(mIntent);
	            	}else if(pString.equals("fail :")){
	            		Log.d("fail", pString);
	            		pString = pString.replace("fail:", "");
	            		throw new Exception(pString);
	            	}else{
	            		throw new Exception(pString);
	            	}
	            	
	        	}else{
	        		
	        		throw new Exception("network error");
	        	}
	        	
	        }catch(SocketTimeoutException se){
	        	
	        	result[1] = "network error";
	        	
	        }catch(Exception e){
	        	
	        	result[1] = e.getMessage();
	        	
	        }finally{
	        	
	        	if(conn != null)
	        		conn.disconnect();

	        	if(br != null){
	        		try {
	        			br.close();
					} catch (Exception e2) {
						// TODO: handle exception
						result[1] = e2.getMessage();
					}
	        	}
	        }
	      
	        return result;
		}
	}
}
